package com.caiyi.financial.nirvana.sms.service;

import com.caiyi.financial.nirvana.sms.base.service.BaseService;
import com.caiyi.financial.nirvana.sms.entity.SmsWhiteList;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.mapper.SmsWhiteListMapper;
import com.caiyi.financial.nirvana.sms.querybean.PageBean;
import com.caiyi.financial.nirvana.sms.querybean.QueryMsgBean;
import com.youyu.common.api.Result;
import com.caiyi.financial.nirvana.sms.util.ValidateUtil;
import com.github.pagehelper.PageHelper;
import com.youyu.common.enums.BaseResultCode;
import com.youyu.common.exception.BizException;
import com.youyu.common.utils.YyAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SmsWhiteListService extends BaseService<SmsWhiteList> {

    @Autowired
    private SmsWhiteListMapper smsWhiteListMapper;

    public void addSmsWhiteList(SmsWhiteList smsWhiteList) {
        YyAssert.isFalse(!ValidateUtil.isPhone(smsWhiteList.getPhone()), ReturnCodeEnum.PARAMS_ERROR.code, "电话号码格式有误");
        int count = smsWhiteListMapper.getSmsWhiteList(smsWhiteList.getPhone(), smsWhiteList.getAccount());
        YyAssert.isFalse(count > 0, ReturnCodeEnum.FAILED.code, "此电话号码已经加入白名单！");
        String key = String.format(JedisKey.SMS_WHITE_LIST_ACCOUNT, smsWhiteList.getAccount());
        JedisService.sadd(key, smsWhiteList.getPhone());
        insertByEntitySelective(smsWhiteList);
    }

    public void delSmsWhiteList(String phone, String account) {
        //redis中删除accountBlacklist
        String key = String.format(JedisKey.SMS_WHITE_LIST_ACCOUNT, account);
        JedisService.srem(key, phone);
        smsWhiteListMapper.delSmsWhiteList(phone, account);
    }

    public PageBean<SmsWhiteList> searchSmsWhiteList(QueryMsgBean bean) {
        PageBean<SmsWhiteList> pageBean = null;
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsWhiteList> list = smsWhiteListMapper.searchSmsWhiteList(bean);
        pageBean = new PageBean<>(list);
        return pageBean;
    }
}
